package mms.farina.thecell;

import java.io.IOException;
import java.io.InterruptedIOException;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;



import mms.farina.thecell.activities.MainActivity;
import mms.farina.thecell.messages.CustomMessage;
import mms.farina.thecell.messages.MySerialization;
import mms.farina.thecell.services.ReceiveService;
import mms.farina.thecell.support.ErrorCodes;
import android.os.Message;

/**Classe usata per l'invio dei messaggi di autenticazione*/
public class Sender {


	public DatagramSocket socket = null;
	CustomMessage message=null;
	private int toPort=ReceiveService.PORT_NEIGHBOR;
	private String toIp=ReceiveService.IP_NEIGHBOR;
	public boolean state=true;


	public Sender(){
		
	}

	public Sender(CustomMessage message){

		this.message=message;
	}

	public CustomMessage getMessage() {
		return message;
	}

	public void setMessage(CustomMessage message) {
		this.message = message;
	}


	/**Invia e riceve un messaggio: Usato in fase di autenticazione*/
	private Runnable mTask2 = new Runnable() {
		public void run() {

			byte[] buf;
			DatagramPacket packet;
			buf = new byte[4096];
			try {
				buf=MySerialization.SerializeMessage(message);
				socket = new DatagramSocket();
				packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(toIp), toPort);
				socket.send(packet);
				byte[] buf2 = new byte[4096];
				packet = new DatagramPacket(buf2, buf2.length);
				socket.setSoTimeout(30*100);
				socket.receive(packet);
				message=MySerialization.DeSerializeSimpleCustomMessage(buf2);
				socket.close();
				state=false;

			} catch (InterruptedIOException e){
				state=false;
				message=null;
				sendError(ErrorCodes.SERVER_UNREACHABLE_MSG, ErrorCodes.SERVER_UNREACHABLE);
				e.printStackTrace();
			} catch (SocketException e) {
				state=false;
				message=null;
				sendError(ErrorCodes.SOCKET_OPENING_ERROR_MSG, ErrorCodes.SOCKET_OPENING_ERROR);
				e.printStackTrace();
			} catch (IOException e) {
				state=false;
				message=null;
				sendError(ErrorCodes.GENERIC_ERROR_MSG, ErrorCodes.GENERIC_ERROR);
				e.printStackTrace();
			}

		}
	};
	

	public CustomMessage sendRecvGenericMessage(CustomMessage message, String ip, int port){
		Thread senderThread = new Thread(mTask2, "SenderReceiveThread");
		this.message=message;
		toIp=ip;
		toPort=port;
		senderThread.start();
		while(state);
		state=true;
		return this.message;

	}


	private void sendError(String message, int code){
		Message m=new Message();
		m.obj=message;
		m.what=code;
		MainActivity.regProgressHandler.sendMessage(m);
	}




}
